﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;

// 学生类
public class Student
{
    public string StudentId { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string Class { get; set; }

    public override string ToString()
    {
        return $"学号：{StudentId}，姓名：{Name}，年龄：{Age}，班级：{Class}";
    }
}

class Program
{
    static List<Student> students = new List<Student>();
    static string fileName = "students.json";

    static void Main(string[] args)
    {

        students.Add(new Student { StudentId = "001", Name = "张三", Age = 20, Class = "一班" });
        students.Add(new Student { StudentId = "002", Name = "李四", Age = 19, Class = "二班" });

        Console.WriteLine("原始数据：");
        DisplayStudents();

 
        SaveToJson();

     
        students.Clear();
        Console.WriteLine("\n清空后的数据：");
        DisplayStudents();

   
        LoadFromJson();

        Console.WriteLine("\n从文件加载后的数据：");
        DisplayStudents();

        Console.WriteLine("\n按任意键退出...");
        Console.ReadKey();
    }


    static void SaveToJson()
    {
        string json = JsonSerializer.Serialize(students, new JsonSerializerOptions { WriteIndented = true });
        File.WriteAllText(fileName, json);
        Console.WriteLine($"\n数据已保存到 {fileName}");
    }

  
    static void LoadFromJson()
    {
        if (File.Exists(fileName))
        {
            string json = File.ReadAllText(fileName);
            students = JsonSerializer.Deserialize<List<Student>>(json);
            Console.WriteLine($"\n从 {fileName} 加载数据成功");
        }
        else
        {
            Console.WriteLine("\n文件不存在");
        }
    }


    static void DisplayStudents()
    {
        if (students.Count == 0)
        {
            Console.WriteLine("没有学生数据");
            return;
        }

        foreach (var student in students)
        {
            Console.WriteLine(student);
        }
    }
}